﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LotteryVote.Entity;
using System.Data.SqlClient;

namespace LotteryVote.Data
{
    public class GameBetLimitDataAccess : DataBase
    {
        public void Insert(GameBetLimit limit)
        {
            string sql = string.Format(@"INSERT INTO {0} ({1},{2},{3},{4}) VALUES (@{1},@{2},@{3},@{4})", GameBetLimit.TABLENAME,
                GameBetLimit.USERID, GameBetLimit.GAMEPLAYWAYID, GameBetLimit.COMPANYTYPE, GameBetLimit.LIMITVALUE);
            base.ExecuteNonQuery(sql, new SqlParameter(GameBetLimit.USERID, limit.UserId),
                new SqlParameter(GameBetLimit.GAMEPLAYWAYID, limit.GamePlayWayId),
                new SqlParameter(GameBetLimit.COMPANYTYPE, limit.CompanyType),
                new SqlParameter(GameBetLimit.LIMITVALUE, limit.LimitValue));
        }

        public void Delete(int userId, int companyTypeId)
        {
            string sql = string.Format(@"DELETE {0} WHERE {1}=@{1} AND {2}=@{2}", GameBetLimit.TABLENAME, GameBetLimit.USERID, GameBetLimit.COMPANYTYPE);
            base.ExecuteNonQuery(sql, new SqlParameter(GameBetLimit.USERID, userId),
                new SqlParameter(GameBetLimit.COMPANYTYPE, companyTypeId));
        }

        public void Clear(int gameplaywayId)
        {
            string sql = string.Format(@"DELETE {0} WHERE {1}=@{1}", GameBetLimit.TABLENAME, GameBetLimit.GAMEPLAYWAYID);
            base.ExecuteNonQuery(sql, new SqlParameter(GameBetLimit.GAMEPLAYWAYID, gameplaywayId));
        }

        public IList<GameBetLimit> ListLimitByUser(int userId)
        {
            string sql = string.Format(@"SELECT * FROM {0} WHERE {1}=@{1}", GameBetLimit.TABLENAME, GameBetLimit.USERID);
            return base.ExecuteList<GameBetLimit>(sql, new SqlParameter(GameBetLimit.USERID, userId));
        }
        public IList<GameBetLimit> GetParentGameLimit(int childUserId, CompanyType companyType)
        {
            string sql = string.Format(@"SELECT GBL.* FROM {0} GBL
JOIN (SELECT UR.* FROM {1} AS UR,(SELECT * FROM {1} WHERE {2}=@{2}) AS T
WHERE UR.{2}=T.{3}) TU ON TU.{2}=GBL.{4} AND GBL.{5}=@{5}", GameBetLimit.TABLENAME, User.TABLENAME, User.USERID, User.PARENTID, GameBetLimit.USERID,
                   GameBetLimit.COMPANYTYPE);
            return base.ExecuteList<GameBetLimit>(sql, new SqlParameter(User.USERID, childUserId),
                new SqlParameter(GameBetLimit.COMPANYTYPE, (int)companyType));
        }
    }
}
